#include "Camera.h"

void Camera :: UpdateCamera ( float msec ) {

	pitch	-= ( Window :: GetMouse () -> GetRelativePosition (). y );
	yaw		-= ( Window :: GetMouse () -> GetRelativePosition (). x );

	pitch = min ( pitch , 90.0f );
	pitch = max ( pitch , -90.0f );

	// Window::GetMouse () -> SetAbsolutePosition(800/2, 600/2);

	if( yaw < 0) {
		yaw += 360.0f ;
	}
	if( yaw > 360.0f ) {
		yaw -= 360.0f ;
	}

	if( Window :: GetKeyboard () -> KeyDown ( KEYBOARD_W )) {
		position += Matrix4 :: Rotation ( yaw , Vector3 (0.0f ,1.0f ,0.0f )) * Vector3 (0.0f ,0.0f , -1.0f ) * msec ;
	}
	if( Window :: GetKeyboard () -> KeyDown ( KEYBOARD_S )) {
		position -= Matrix4 :: Rotation ( yaw , Vector3 (0.0f ,1.0f ,0.0f )) * Vector3 (0.0f ,0.0f , -1.0f ) * msec ;
	}

	if( Window :: GetKeyboard () -> KeyDown ( KEYBOARD_A )) {
		position += Matrix4 :: Rotation ( yaw , Vector3 (0.0f ,1.0f ,0.0f )) * Vector3 ( -1.0f ,0.0f ,0.0f ) * msec ;
	}
	if( Window :: GetKeyboard () -> KeyDown ( KEYBOARD_D )) {
		position -= Matrix4 :: Rotation ( yaw , Vector3 (0.0f ,1.0f ,0.0f )) * Vector3 ( -1.0f ,0.0f ,0.0f ) * msec ;
	}

	if( Window :: GetKeyboard () -> KeyDown ( KEYBOARD_SPACE )) {
		position . y += msec ;
	}
	if( Window :: GetKeyboard () -> KeyDown (  KEYBOARD_SHIFT )) {
		position . y -= msec ;
	}
}

Matrix4 Camera::BuildViewMatrix () {					
	if(FreeView == true){
		return Matrix4::Rotation(-pitch , Vector3(1,0,0)) *
			   Matrix4::Rotation(-yaw, Vector3(0,1,0)) *
			   Matrix4::Translation(-position);
	}else{
		float sinViewDegree = asin(FollowViewVector.x)* 180/M_PI;

		if(FollowViewVector.z > 0 && FollowViewVector.x < 0){
			sinViewDegree = -(sinViewDegree + 180);
		}

		if(FollowViewVector.z > 0 && FollowViewVector.x > 0){
			sinViewDegree = -(sinViewDegree + 180);
		}
		position.y=position.y+100;
		yaw = - sinViewDegree;
		return	Matrix4::Rotation(-Cpitch, Vector3 (1 ,0 ,0)) * 
				Matrix4::Rotation(-Cyaw, Vector3(0, 1, 0)) * 
				Matrix4::Rotation(sinViewDegree, Vector3(0, 1, 0)) *
				Matrix4::Translation(-(position + ModelLeft * CameraShiftAmong));
	}
	
	//Matrix4::BuildViewMatrix(ObjectPos - FollowViewVector*80 + Vector3(0,60,0), ObjectPos, Vector3(0,0.5,0))	
	//change
}

Vector3 Camera::GetForwardVector()
{
	Vector3 fwd = Vector3(0,0,1);
	Vector3 forward = Matrix4::Rotation(yaw, Vector3(0,1,0)) * Matrix4::Rotation(pitch, Vector3(1,0,0)) * fwd;

	return forward;
}

Vector3 Camera::GetForwardVectorYaw()
{
	Vector3 fwd = Vector3(0,0,1);
	Vector3 forward = Matrix4::Rotation(yaw, Vector3(0,1,0)) *  fwd;
	return forward;
}